﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using KPIS.GERP.SERVICE.DAL;
using KPIS.GERP.SERVICE.Model;

namespace KPIS.GERP.SERVICE.WorkflowService.WCFService
{
    [ServiceContract]
    public interface ITempService
    {
        [OperationContract]
        Model.hrm_ps_employees GetEmployeeByCitizen(string citizen);

        [OperationContract]
        List<Model.message> GetMessages(string citizen);

        [OperationContract]
        Model.message GetMessage(int message_seq);

        [OperationContract]
        void MarkHasBeenRead(int message_seq, string citizen);

        [OperationContract]
        hrm_ps_absence GetHrmPsAbsence(int ref_seq);

        [OperationContract]
        List<Model.sys_sc_users> GetSysScUser();

        [OperationContract]
        List<hrm_ps_absence> GetHrmPsAbsences(string absence_seq, string absence_type_seq, string citizen, string bgm_year
                                              , bool isGetHrmPsAbsenceType, bool isGetHrmPsEmployees);

        [OperationContract]
        int GetMessageUnreadCount(string citizen);

        [OperationContract]
        int GetMessageUnwarnCount(string citizen);

        [OperationContract]
        List<message> GetMessageByEmployeeCitizen(string citizen);

        [OperationContract]
        void MarkAsRead(string citizen);

        [OperationContract]
        List<rule_approve> RuleApproveList(out List<hrm_ps_employees> employeeses,
                                           out List<sys_sc_users> userses,
                                           out List<rule_approve_group> ruleApproveGroups,
                                           out List<rule_approve_type> ruleApproveTypes);

        [OperationContract]
        List<Dictionary<string, string>> GetApprover(int rule_approve_type, string citizen);

        [OperationContract]
        IEnumerable<rule_approve_group> GetRuleApproveGroup(int rule_approve_group_seq);
    }

    public class TempService : ITempService
    {
        #region Implementation of ITempService

        private int GetEmpSeqByCitizen(string citizen)
        {
            var emp = GetEmployeeByCitizen(citizen);
            if(emp == null) throw new Exception("No employee of this user");
            return emp.emp_seq;
        }

        public hrm_ps_employees GetEmployeeByCitizen(string citizen)
        {
            var bllEmployee = new KPIS.GERP.SERVICE.DAL.Employee();
            var employee = bllEmployee.GetHrmPsEmployeeLite(new Model.hrm_ps_employees() {citizen = citizen, record_status = "U"}).FirstOrDefault();
            return employee;
        }

        public List<message> GetMessages(string citizen)
        {
            int emp_seq = GetEmpSeqByCitizen(citizen);
            var dalMessage = new DAL.Message();
            List<message> list_message = dalMessage.GetMessage(null, null, emp_seq.ToString(), null, null, null
                                                               , true, true, false, false, false, false).
                OrderByDescending(m => m.message_seq).ToList();
            return list_message;
        }

        public message GetMessage(int message_seq)
        {
            var dalMessage = new DAL.Message();
            message result = dalMessage.GetMessage(message_seq.ToString(), null, null, null, null, null
                                                   , true, true, false, false, false, false).
                OrderByDescending(m => m.message_seq).FirstOrDefault();
            return result;
        }

        public void MarkHasBeenRead(int message_seq, string citizen)
        {
            int emp_seq = GetEmpSeqByCitizen(citizen);
            var dalMessage = new DAL.Message();
            dalMessage.ReadMessage(message_seq.ToString(), emp_seq.ToString());
        }

        public hrm_ps_absence GetHrmPsAbsence(int ref_seq)
        {
            var result = new DAL.Absence().GetHrmPsAbsence(ref_seq.ToString(), "", "", "",
                                                           true, true).FirstOrDefault();
            return result;
        }

        public List<sys_sc_users> GetSysScUser()
        {
            return new DAL.User().GetUser(null, null, null, null, false);
        }

        public List<hrm_ps_absence> GetHrmPsAbsences(string absence_seq, string absence_type_seq, string citizen, string bgm_year
                                                     , bool isGetHrmPsAbsenceType, bool isGetHrmPsEmployees)
        {
            string emp_seq = GetEmpSeqByCitizen(citizen).ToString();
            return new DAL.Absence().GetHrmPsAbsence(absence_seq, absence_type_seq, emp_seq, bgm_year
                                                     , isGetHrmPsAbsenceType, isGetHrmPsEmployees);
        }

        public int GetMessageUnreadCount(string citizen)  /***/
        {
            string strEmpSeq = GetEmpSeqByCitizen(citizen).ToString();
            var dalMessage = new DAL.Message();

            return dalMessage.GetMessage(null, null, null, null, null, null
                                         , false, false, false, false, false, false)
                .Count(o => o.to_emp_seq.ToString() == strEmpSeq
                            && o.message_status != "0");

        }

        public int GetMessageUnwarnCount(string citizen)
        {
            int intEmpSeq = GetEmpSeqByCitizen(citizen);

            var dalMessage = new DAL.Message();

            var messages = dalMessage.GetMessage(null, null, null, null, null, null
                                                 , false, false, false, false, false, false);

            int intUnwarnCount = messages.Count(o => o.to_emp_seq == intEmpSeq
                                                     && o.message_status == "1");

            dalMessage.WarnMessage(intUnwarnCount, intEmpSeq.ToString(), intEmpSeq.ToString());

            return intUnwarnCount;
        }

        public List<message> GetMessageByEmployeeCitizen(string citizen)
        {
            int emp_seq = GetEmpSeqByCitizen(citizen);
            //var dalMessage = new DAL.Message();
            //return dalMessage.GetMessage(null, null, emp_seq.ToString(), null, null, null
            //                             , false, false, false, false, true, false);
            var dalMessage = new DAL.Message();
            return dalMessage.GetMessageByEmpSeq(emp_seq);
        }

        public void MarkAsRead(string citizen)
        {
            int emp_seq = GetEmpSeqByCitizen(citizen);
            var dalMessage = new DAL.Message();
            dalMessage.WarnMessage(10000, emp_seq.ToString(), emp_seq.ToString());
        }

        public List<rule_approve> RuleApproveList(out List<hrm_ps_employees> employeeses,
                                                  out List<sys_sc_users> userses,
                                                  out List<rule_approve_group> ruleApproveGroups,
                                                  out List<rule_approve_type> ruleApproveTypes)
        {

            var ruleApproveDal = new DAL.RuleApprove();
            var employeeDal = new DAL.Employee();
            employeeses = employeeDal.GetHrmPsEmployeeLite();
            userses = employeeDal.GetUsers();
            ruleApproveGroups = ruleApproveDal.GetRuleApproveGroup(null);
            ruleApproveTypes = ruleApproveDal.GetRuleApproveType(null, null, false);
            var ruleApproves = ruleApproveDal.GetRuleApprove("", "", true, false, false);
            return ruleApproves;
        }

        public List<Dictionary<string, string>> GetApprover(int rule_approve_type_seq, string emp_citizen_ask)
        {
            var ruleApproveDal = new DAL.RuleApprove();
            var employeeDal = new DAL.Employee();
            var employeeList = employeeDal.GetHrmPsEmployeeLite();
            var positionList = employeeDal.GetHrmMpPositions(null, null, null, null, null, null, null, null, false, false, false, false, false, false);
            //var employeeses = employeeDal.GetHrmPsEmployeeLite();
            //var userses = employeeDal.GetUsers();
            //var ruleApproveGroups = ruleApproveDal.GetRuleApproveGroup(null);
            //var ruleApproveTypes = ruleApproveDal.GetRuleApproveType(rule_approve_type_seq.ToString(), null, false);
            var ruleApproves = ruleApproveDal.GetRuleApprove("", rule_approve_type_seq.ToString(), true, false, false);
            var result = new List<Dictionary<string, string>>();
            foreach (rule_approve r in ruleApproves)
            {
                var eachStep = new Dictionary<string, string>();
                eachStep.Add("rule_approve_type_name", r.rule_approve_type.rule_approve_type_name);
                eachStep.Add("approver_type", Convert.ToString(r.approver_type));
                eachStep.Add("step", r.step.ToString());
                eachStep.Add("approver_seq", Convert.ToString(r.approver_seq));

                if (r.approver_type == "2")
                {
                    var empObj = (from emp in employeeList where emp.pos_seq == r.approver_seq select emp).FirstOrDefault();
                    var posObj = (from pos in positionList where pos.pos_seq == r.approver_seq select pos).FirstOrDefault();
                    eachStep.Add("emp_name", empObj == null ? "<span style='color:red'>ไม่พบผู้อนุมัติตามรหัสที่ระบุ</span>" : empObj.full_name);
                    eachStep.Add("pos_name", posObj != null ? posObj.pos_name : "<span style='color:red'>ไม่พบตำแหน่ง</span>");
                }
                else if (r.approver_type == "5")
                {
                    int emp_seq = GetEmpSeqByCitizen(emp_citizen_ask);
                    var jobSiteSeqOfEmployee = new Employee().GetJobSiteSeqFromEmpSeq(emp_seq);
                    var employeeHead = new Employee().LoadJobSiteHeadEmployee(jobSiteSeqOfEmployee);
                    var posHeadObj = (from pos in positionList where pos.pos_seq == employeeHead.pos_seq select pos).FirstOrDefault();
                    var posHeadName = posHeadObj != null ? posHeadObj.pos_name : "";
                    eachStep.Add("emp_name", employeeHead == null ? "<span style='color:red'>ไม่พบผู้อนุมัติหัวหน้าสำนักของหน่วยงาน " + jobSiteSeqOfEmployee + ":" + posHeadName + "</span>" : employeeHead.full_name);
                    eachStep.Add("pos_name", !string.IsNullOrWhiteSpace(posHeadName) ? posHeadName : "<span style='color:red'>ไม่พบตำแหน่ง</span>");
                }
                else
                {
                    eachStep.Add("emp_name", string.Empty);
                    eachStep.Add("pos_name", "<span style='color:red'>คำนวนจากตอนสร้างคำขอ</span>");
                }


                switch (r.approver_type)
                {
                        // (1 = หัวหน้า, 2 = ตำแหน่ง, 3 สังกัด, 4, กลุ่ม)
                    case "1":
                        eachStep.Add("approver_type_name", "โดยหัวหน้า/ผู้อำนวยการ");
                        break;
                    case "2":
                        eachStep.Add("approver_type_name", "ระบุตำแหน่ง");
                        break;
                    case "3":
                        eachStep.Add("approver_type_name", "กระจายให้หน่วยงาน");
                        break;
                    case "4":
                        eachStep.Add("approver_type_name", "กระจายให้กลุ่มของผู้ใช้");
                        break;
                    case "5":
                        eachStep.Add("approver_type_name", "ส่งถึงหัวหน้าสำนัก");
                        break;
                    default:
                        eachStep.Add("approver_type_name", r.approver_type_name);
                        break;
                }
                result.Add(eachStep);
            }
            return result;
        }

        public IEnumerable<rule_approve_group> GetRuleApproveGroup(int rule_approve_group_seq)
        {
            return new DAL.RuleApprove().GetRuleApproveGroup(Convert.ToString(rule_approve_group_seq));
        }

        #endregion
    }
}